import Vue from 'vue'
import VueRouter from 'vue-router'
import helper from '@/helper/helper'
import store from '@/store'
import error from './error'
import { getToken } from '@/utils/cookies'
const LAYOUT = () => import('@/components/layout')

Vue.use(VueRouter)

// 基础路由
export const constantRoutes = [
  ...error,
  {
    path: '/',
    name: 'default',
    redirect: '/home',
    component: LAYOUT,
    children: [
      {
        path: 'home',
        name: 'home',
        component: () => import('@/views/home')
      },
      {
        path: 'result',
        name: 'result',
        component: () => import('@/views/result')
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/Index')
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('@/views/register/Index')
  }
]

const createRouter = () => new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [...constantRoutes]
})

const router = createRouter()
// 重置路由
export function resetRouter () {
  const newRouter = createRouter();
  (router).matcher = (newRouter).matcher // reset router
}
const white = ['login', 'index', '403', 'Register']
router.beforeEach(async (to, from, next) => {
  if (to.name === 'login' || to.name === 'register' || localStorage.getItem('token')) {
    next()
  } else {
    next({ name: 'login' })
  }
  // next({ name: 'login' })
})

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

export default router
